import logging
from django.db.models import F
from django.forms import model_to_dict

from base.api.utils import update_customer_consume_points
from finance.models import CapitalAccount, Journal, HistoryAccount

logger = logging.getLogger("django")


def get_account(account_id):
    return CapitalAccount.objects.filter(id=account_id).first()


def save_history_account(account_id, money=0):
    """保存历史信息"""
    account = CapitalAccount.objects.filter(id=account_id).first()
    dict_acc = model_to_dict(account)
    dict_acc.pop("id")
    dict_acc["money"] = money
    logger.info("save_history_account: {}".format(dict_acc))
    HistoryAccount.objects.create(**dict_acc)


def update_account(account_id, actual_amount):
    """采购修改账户余额"""
    logger.info("update_account: account_id:{}--actual:{}".format(account_id, actual_amount))
    save_history_account(account_id, -actual_amount)
    CapitalAccount.objects.filter(id=account_id).update(balance=F("balance") - actual_amount)


def increase_account_amount(account_id, amount, customer_id=None):
    """销售增加账户余额"""
    logger.info("increase_account_amount: account_id:{}--actual:{}".format(account_id, amount))
    save_history_account(account_id, amount)
    CapitalAccount.objects.filter(id=account_id).update(balance=F("balance") + amount)
    update_customer_consume_points(customer_id, amount)


def create_journal(**data):
    """保存流水信息"""
    order_no = data.pop("order_no")
    created = data.pop("created")
    if not created:
        data.pop("balance")
    Journal.objects.update_or_create(order_no=order_no, defaults=data)


def remove_journal(order_no):
    """删除流水记录"""
    logger.info("remove_journal: order_no:{}".format(order_no))
    Journal.objects.filter(order_no=order_no).delete()
